package com.whut.utils;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;

import java.util.Date;
import java.util.Random;
/*
pom.xml
<dependency>
  <groupId>com.aliyun</groupId>
  <artifactId>aliyun-java-sdk-core</artifactId>
  <version>4.0.3</version>
</dependency>
*/

/**
* 发送验证码的类
*@author fuzhenjie
*@date 19.9.12 1:28(GMT)
*/
public class SendSms {


    /**
    * 发送验证码,并返回验证码（如果发送成功）
    *@author fuzhenjie
    *@date 19.9.12 1:42(GMT)
    *@param phone 手机号
    *@return com.alibaba.fastjson.JSONObject
    */
    public static JSONObject send(String phone) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI4FqJPKj5VE1HHCUKbcrw", "EMLN5hqqE6aGk80EnERX2upr5obN2z");
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers",phone );
        request.putQueryParameter("SignName", "毅瑞建设工程咨询");
        request.putQueryParameter("TemplateCode", "SMS_173478301");
        String v_code = generateRandom();
        request.putQueryParameter("TemplateParam", "{code:"+v_code+"}");
        try {
            CommonResponse response = client.getCommonResponse(request);
            JSONObject jsonObject = JSONObject.parseObject(response.getData());
            jsonObject.put("v_code",v_code);
            return jsonObject;
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return JSONObject.parseObject("{\"Message\":\"ERR\"}");
    }

    /**
    * 生成真随机数
    *@author fuzhenjie
    *@date 19.9.12 1:42(GMT)
    *@return java.lang.String
    */
    private static String generateRandom(){
        //用当前的时间作为种子，生成真随机数
        Random random = new Random(new Date().getTime());
        int code = random.nextInt(8999);
        int code1 = code + 1000;
        return Integer.toString(code1);
    }

}